import { Injectable, Compiler, Injector } from '@angular/core';
import { ContentFormService } from './content-form.Service';
import {
    ContentServiceProxy, CreateOrUpdateInput, 
    GetContentForEditInput, SetStatusWithMenuIdInput,
    PreviewTokenInput, ContentSyncServiceProxy, ManualSyncTwoInput, 
    PagedMotherSiteContentInput, NameValueDto, ManualSyncInput, PreviewServiceProxy
} from '@shared/service-proxies/service-proxies';
import { finalize } from 'rxjs/operators';
import { AppConsts } from '@shared/AppConsts';
import { IContentDetailComponent } from './IContentDetailComponent';
import { MessageService } from 'abp-ng2-module';
import { AppLocalizationService } from '@app/shared/common/localization/app-localization.service';
import { ContentDetailModalComponent } from './detail/content-detail-modal.component';
import { AppNotifyService } from '@shared/utils/service/app-notify.service';
import { FileUploadHelper } from '@shared/helpers/FileUploadHelper';
import { ManualSyncModalComponent } from '../shared/manual-sync/manual-sync-modal.component';
import { AppBsModalService } from '@shared/common/appBsModal/app-bs-modal.service';

@Injectable()
export class AppContentDetailService {

    constructor(
        private _contentFormService: ContentFormService,
        private _contentServiceProxy: ContentServiceProxy,
        private _previewServiceProxy: PreviewServiceProxy,
        private message: MessageService,
        private notify: AppNotifyService,
        private compiler: Compiler,
        private _modalService: AppBsModalService,
        private _contentSyncService: ContentSyncServiceProxy,
        private _appLocalizationService: AppLocalizationService) {

    }

    initDetailPage(vm: IContentDetailComponent, vcInjector: Injector, isModal: boolean, callback: { (): void }) {

        if (isModal) {
            // 先打开弹窗
            if (callback) {
                callback();
            }
        } 

        let input = new GetContentForEditInput({
            menuId: vm.kind,
            customKey: vm.customKey,
            relateId: vm.relateId,
            id: vm.id
        });
        vm.isLoading = true;
        this._contentServiceProxy.getContentForEdit(input)
            .pipe(finalize(() => vm.isLoading = false))
            .subscribe(result => {
                if (!result.id && vm.id) {
                    //id有误
                    if (vm.pageConfig.isInfo && !vm.relateId) {
                        vm.goToNewPage();
                    }
                } else {

                    vm.hiddenDetail = false;

                    this._contentFormService.afterLoadData(vm.pageConfig.detail, result);
                    vm.data = result;
                    if (vm.data.id) {
                        vm.randomId = vm.data.id;
                        vm.isTemporary = false;
                        vm.customKey == vm.data.key;
                    }else{
                        vm.randomId = FileUploadHelper.newGuid();
                        vm.isTemporary = true;
                    }

                    let html = this._contentFormService.getDetailPageTemplate(vm.pageConfig);
                    //console.info(html);
                    if (vm.cmpRef) {
                        vm.cmpRef.destroy();
                    }

                    let tempFunc = function () {
                        this.data = vm.data;
                        this.permissionDic = vm.permissionDic;
                        this.randomId = vm.randomId;
                        this.isTemporary = vm.isTemporary;
                        this.kind = vm.kind;
                        this.customKey = vm.customKey;
                        this.relateId = vm.relateId;
                        this.id = vm.id;
                        this.dataSynchronous = vm.dataSynchronous;
                    };

                    this._contentFormService._diyFormService.createFormComponentFactory(this.compiler, html, tempFunc).then(factory => {
                        const injector = Injector.create({ providers: [], parent: vcInjector });
                        const cmpRef = vm.vc.createComponent(factory, 0, injector, []);

                        cmpRef.instance.name = "dynamic-content-component";

                        vm.cmpRef = cmpRef;
                    });

                    //this._contentFormService.initCtrls(vm);
                }
            });
    }

    //-- action

    //保存并预览
    previewItem(vm: IContentDetailComponent) {
        if (!vm.saving && !vm.isLoading) {

            if ((vm.permissionDic['Pages_Manage_Content_Create'] && !vm.id) || vm.permissionDic['Pages_Manage_Content_Update'] && vm.id) {
                vm.saving = true;
                var input = this.getFormDataToSave(vm);

                this._contentServiceProxy.createOrUpdate(input)
                    .pipe(finalize(() => vm.saving = false))
                    .subscribe((result) => {
                        this.notify.success(this._appLocalizationService.l('SavedSuccessfully'));
                        if(vm.id !== result){
                            vm.id = result;
                            if(vm.isModal){
                                this.initDetailPage(vm, vm.vc.injector, true, null);
                            }else{
                                this.initDetailPage(vm, vm.vc.injector, false, null);
                            }
                        }

                        var tokenInput=new PreviewTokenInput({menuId:vm.data.menuId,auxId:vm.data.auxId,id:result,key:vm.data.key});
                        this._previewServiceProxy.getPreviewToken(tokenInput)
                            .subscribe((tokenResult) => {
                                this.notify.success(this._appLocalizationService.l('SavedSuccessfully'));
                                window.open(AppConsts.remoteServiceBaseUrl + "/Preview/Index?token=" + tokenResult.token);
                            });


                    });
            }

        }
    }

    // 保存
    saveItem(vm: IContentDetailComponent) {
        if (!vm.saving && !vm.isLoading) {
            vm.saving = true;
            var input = this.getFormDataToSave(vm);

            this._contentServiceProxy.createOrUpdate(input)
                .pipe(finalize(() => vm.saving = false))
                .subscribe((result) => {
                    if(!vm.id){
                        vm.id = result;
                    }
                    this.notify.success(this._appLocalizationService.l('SavedSuccessfully'));
                    this.goBack(vm, true);
                });
        }
    }

    private getFormDataToSave(vm: IContentDetailComponent): CreateOrUpdateInput {

        let input = { "menuId": vm.kind, "customKey": vm.customKey, "relateId": vm.relateId, "randomId": vm.randomId };
        if (vm.id) {
            input['id'] = vm.id;
        } else {
            input['id'] = null;
        }

        let field: { [key: string]: any } = {};
        for (let key in vm.data) {
            field[key] = vm.data[key];
        }
        // 数据处理：html编码，时间等格式化
        this._contentFormService.beforeSubmit(vm.pageConfig.detail, field);
        input['values'] = field;

        let result = new CreateOrUpdateInput();
        result.init(input);
        return result;
    }


    deleteSingle(vm: IContentDetailComponent) {
        if (vm.id) {
            this.message.confirm(this._appLocalizationService.l('DeleteWarningMessage'), this._appLocalizationService.l('AreYouSure'),
                (isConfirmed) => {
                    if (!isConfirmed) return;
                    this._contentServiceProxy.deleteListAysnc(vm.kind, vm.relateId, [vm.id])
                        .subscribe(() => {
                            if (vm.isModal) {
                                this.goBack(vm, true);
                            } else {
                                vm.goToNewPage();
                            }

                            this.notify.success(this._appLocalizationService.l('SuccessfullyDeleted'));
                        });
                })
        }
    }

    changeState(vm: IContentDetailComponent, state: boolean) {
        if (vm.id) {
            let msg: string;
            if (state) {
                msg = this._appLocalizationService.l('ReleaseWarningMessage');
            }
            else {
                msg = this._appLocalizationService.l('UndoReleaseWarningMessage');
            }
            this.message.confirm(msg, this._appLocalizationService.l('AreYouSure'),
                (isConfirmed) => {
                    if (!isConfirmed) return;

                    let input = new SetStatusWithMenuIdInput();
                    input.menuId = vm.kind;
                    input.idList = [vm.id];
                    input.isActive = state;

                    this._contentServiceProxy.setStatus(input)
                        .subscribe(() => {
                            this.goBack(vm, true);
                            if (state) {
                                this.notify.success(this._appLocalizationService.l('ReleaseSuccessfully'));
                            } else {
                                this.notify.success(this._appLocalizationService.l('CancelReleaseSuccessfully'));
                            }
                        });
                })
        }
    }
    
    synchorization(vm: IContentDetailComponent) {
        const bsModalRef = this._modalService.show(ManualSyncModalComponent, {
            backdrop: 'static', class: 'modal-xl'
        });

        let params = new PagedMotherSiteContentInput();
        params.menuId = vm.kind;
        params.customKey = vm.customKey;
        params.relateId = vm.relateId;

        let keyList : NameValueDto[] = [];

        bsModalRef.content.configure({
            defaultParam: params,
            getDataFunc: (t)=> this._contentSyncService.getContentMotherInfo(t),
            getItems: (t)=> t,
            confirmFunc:(t)=> this._contentSyncService.manualContentSynchorize(t),
            keyList: keyList,
            confirmDefaultParam : new ManualSyncInput()
        });
        bsModalRef.content.shown();
        bsModalRef.content.callback = () => {
            vm.refreshData();
        };
    }

    synchorizationById(vm: IContentDetailComponent) {
        this.message.confirm(
            this._appLocalizationService.l('ManualSyncWarningMessage'),
            this._appLocalizationService.l('AreYouSure'),
            (isConfirmed) => {
                if (!isConfirmed) return;
                let manualSyncInput = new ManualSyncTwoInput({
                    id: vm.id,
                    menuId: vm.kind
                });

                this._contentSyncService.manualContentSynchorizeById(manualSyncInput)
                    .subscribe(result => {
                        if (result && result.syncResult) {
                            this.notify.success(this._appLocalizationService.l('ManualSynchorizationSuccessfully'))
                        }
                        else {
                            this.notify.success(this._appLocalizationService.l('ManualSynchorizationFail'))
                        }
                    })
            })
    }

    private goBack(vm: IContentDetailComponent, refresh: boolean) {
        if (vm.isModal) {
            let vm2 = (vm as ContentDetailModalComponent);
            if (refresh) {
                vm2.backListEvent.emit();
            }
            vm2.close();
        }else{
            vm.refreshData();
        }
    }
    //-- action end
}
